package com.shenyue.nbtownlet.model;

import android.content.Context;
import android.os.AsyncTask;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shenyue.nbtownlet.event.BaseListener;
import com.shenyue.nbtownlet.event.ByteListener;
import com.shenyue.nbtownlet.util.Base64;
import com.shenyue.nbtownlet.util.FileUtil;
import com.zhy.http.okhttp.request.RequestCall;

import java.io.File;
import java.util.List;

import id.zelory.compressor.Compressor;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 文件上传
 */

public class FileUploadModel {
    private static final String SMALLTOWN_XCZFILEUPLOAD_SAVEFILE = "SmallTown/XCZFileUpload/SaveFile";
    public static final String SMALLTOWN_XCZFILEUPLOAD_SAVEFILE_ACTION = "$smalltown_xczfileupload_savefile_action$";
    private static boolean stoped = false;

    public static RequestCall upload(final Context context, JSONObject param, final BaseListener listener) {
        return HttpClientExManager.instance().post(AppModel.kBaseURL + "/" + SMALLTOWN_XCZFILEUPLOAD_SAVEFILE, SMALLTOWN_XCZFILEUPLOAD_SAVEFILE_ACTION, param, new BaseListener() {
            @Override
            public void success(String val, String action) {
                if (listener != null)
                    listener.success(val, action);
            }

            @Override
            public void error(String error, String action) {
                if (listener != null)
                    listener.error(error, action);
            }
        });
    }

    public static void stop() {
        stoped = true;
    }

    public static void upload(final Context context, String file, boolean img, final BaseListener listener) {
        stoped = false;
        if(file.startsWith("http")){
            JSONObject data = new JSONObject();
            data.put("FullUrl", file);
            listener.success(data.toString(), SMALLTOWN_XCZFILEUPLOAD_SAVEFILE_ACTION);
            return;
        }
        if (img)
            doCompressor(context, file, listener);
        else
            load(context, new File(file), null, null, 0, listener);
    }

    //文件压缩
    private static void doCompressor(final Context context, final String file, final BaseListener listener) {
        new Compressor(context)
                .compressToFileAsFlowable(new File(file))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<File>() {
                    @Override
                    public void accept(File file) {
                        load(context, file, null, null, 0, listener);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                        new File(file).delete();
                        listener.error("文件压缩失败", SMALLTOWN_XCZFILEUPLOAD_SAVEFILE_ACTION);
                    }
                });
    }

    private static void load(final Context context, final File file, JSONObject param, List<byte[]> list, final int position, final BaseListener listener) {
        if (stoped)
            return;
        if (list == null) {
            ByteFile byteFile = new ByteFile();
            byteFile.setBaseListener(new ByteListener() {
                @Override
                public void success(List<byte[]> val, String action) {
                    load(context, file, null, val, position, listener);
                }

                @Override
                public void error(String error, String action) {

                }
            });
            byteFile.execute(new File[]{file});
            return;
        }

        if (position >= list.size()) {
            file.delete();
            listener.success(param.toString(), SMALLTOWN_XCZFILEUPLOAD_SAVEFILE_ACTION);
            return;
        }

        if (param == null) {
            JSONObject data = new JSONObject();
            data.put("Length", file.length());
            data.put("FileName", file.getName());
            data.put("Data", Base64.encode(list.get(position)));
            data.put("FileSuffix", FileUtil.getExtensionName(file.getName()));
            data.put("Offset", 0);
            param = new JSONObject();
            param.put("file", data.toString());
        } else {
            JSONObject data = JSON.parseObject(param.toString());
            data.put("Data", Base64.encode(list.get(position)));
            param = new JSONObject();
            param.put("file", data.toString());
        }
        final List<byte[]> _list = list;
        FileUploadModel.upload(context, param, new BaseListener() {
            @Override
            public void success(String val, String action) {
                load(context, file, JSON.parseObject(val), _list, position + 1, listener);
            }

            @Override
            public void error(String error, String action) {
                file.delete();
                listener.error(error, SMALLTOWN_XCZFILEUPLOAD_SAVEFILE_ACTION);
            }
        });
    }

    private static class ByteFile extends AsyncTask<File, Integer, String> {
        private ByteListener listener;

        public void setBaseListener(ByteListener listener) {
            this.listener = listener;
        }

        @Override
        protected String doInBackground(File... params) {
            File file = params[0];
            List<byte[]> list = FileUtil.toByte(file);
            listener.success(list, null);
            return null;
        }
    }
}
